#include "qtserialport.h"
#include<QDebug>
#include<QStringList>
QtSerialPort::QtSerialPort(QObject *parent): QThread(parent)
{
        fd=0;
}
int QtSerialPort::open(char *dev)
{
    fd=open_usb(dev);
     qDebug()<<fd;
     return fd;
}
void  QtSerialPort::run()
{
    fd_set rfds;
    struct timeval tv;
    int retval;
    while(1)
    {
        FD_ZERO(&rfds);
        FD_SET(this->fd,&rfds);
        tv.tv_sec=5;
        tv.tv_usec=0;
        retval = select(fd+1,&rfds,NULL,NULL,&tv);
        if(retval < 0)
       {
                 qDebug()<< "select error!\n";
       }
        if(retval == 0)
       {
              // qDebug()<<"No data within 5 seconds!\n";
       }
       if(retval > 0)
       {
           if(FD_ISSET(fd,&rfds))
           {
                    emit readyRecv();
                    qDebug()<<"emit readyRecv"<<'\n';
                    sleep(2);
           }
       }
    }
}

QString QtSerialPort::receive()
{
    char buf[100];
    char tmp;
    int j=0,number=0;
    memset(buf,0,sizeof(buf));
   while((number=read(fd,&tmp,1))>0)
   {
          if(tmp=='#')
             break;
   }
    while((number=read(fd,&tmp,1))>0)
    {
             if(tmp!='$')
                  buf[j++]=tmp;
             else
                   break;
    }
    return QString(QLatin1String(buf));
}
int QtSerialPort::send(char *buf,int len)
{
   return  write(fd,buf,len);
}
